<?php

namespace App\Http\Controllers\Supplier;

use App\Models\BankCard;
use App\Models\Order;
use App\Models\NewAdmin;

use App\Models\OrderBuyoutAudit;
use App\Models\OrderGoods;
use App\Models\OrderLease;
use App\Models\OrderLeaseAudit;

use App\Models\OrderLeasePartial;
use App\Models\OtherWithholdLog;
use App\Models\ShopSms;
use App\Models\YifubaoPay;
use App\Services\AlipayService;
use App\Services\AntchainAtoService;
use App\Services\AntchainService;
use App\Services\AuthService;
use App\Services\ChargeService;
use App\Services\CommonService;
use App\Services\CreditCallService;
use App\Services\GoodsService;
use App\Services\OrderService;
use App\Services\SmsService;
use App\Services\SuningPayService;
use App\Services\WechatService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use chillerlan\QRCode\QRCode;
use chillerlan\QRCode\QROptions;
use Intervention\Image\Facades\Image;

class OrderLeaseController extends BaseController
{
    /**
     * 提前手动支付提交申请
     */
    public function submitLeasePayApply(Request $request){
        if(empty($request['orderId'])||empty($request['leaseId'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
        }

        $userToken = $request->header("SupplierAuth");
        $user = NewAdmin::where(['token'=>$userToken,'type'=>AuthService::MODEL_MERCHANT])->first();
        $user = obToArray($user);

        if(md5($user['mobile'].$request['password']) != $user['password']){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'密码输入错误错误');
        }
        if(empty($request['transaction_id'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请上传交易单号');
        }


        if(empty($request['image_path'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请上传交易图片');
        }

        $order = Order::from('sp_order_2 as o')->where('o.id',$request['orderId'])
            ->select(
                'o.id','o.flow_id','sign_status','pact_url','sign_no','trade_no'
            )
            ->first();
        $order = $order ? $order->toArray() : [];

        if(empty($order)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单不存在');
        }
        if ($order['sign_status']!=2||empty($order['pact_url'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'该订单未签约合同');
        }
        $OrderLease= OrderLease::where('id',$request['leaseId'])->where('order_id',$request['orderId'])
            ->select(
                'id','which_period','status','rent',
            )
            ->first();
        $OrderLease = $OrderLease ? $OrderLease->toArray() : [];
        if(empty($OrderLease)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单不存在');
        }
        if($OrderLease['status']==1&&!empty($OrderLease['pay_time'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'该期已支付');
        }
        $res=WechatService::getFundFlow(trim($request['transaction_id']),$OrderLease['rent']);
        if(!$res){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'交易单号验证失败,用英文逗号分割不同交易单号');
        }
        $add = [
            'order_id'=>$request['orderId'],
            'lease_id'=>$request['leaseId'],
            'sub_remark'=>$request['remark'],
            'lease_id'=>$request['leaseId'],
            'image_path'=>$request['image_path'],
            'transaction_id'=>$request['transaction_id']??'',
            'create_time'=>time(),
            'admin_id'=>$user['id']
        ];
        $OrderLeaseAudit= OrderLeaseAudit::where('lease_id',$request['leaseId'])->where('order_id',$request['orderId'])->value('check_status');
        if($OrderLeaseAudit&&$OrderLeaseAudit['value']===0||$OrderLeaseAudit&&$OrderLeaseAudit['value']===1){
         return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请勿重复提交审核');
        }
//        $res=OrderLeaseAudit::insert($add);
        $audit_id= (new OrderLeaseAudit)->insertGetId($add);
        if($audit_id){

           if($res){
            $res=OrderLease::where('id',$request['leaseId'])
            ->where('order_id',$request['orderId'])
            ->update(['status'=>1,'pay_time'=>time(),'paid_rent'=>$OrderLease['rent'],'pay_type'=>OrderLease::LEASE_PAY_TYPE_WECHAT,'alipay_trade_no'=>$request['transaction_id']]);
               if($res){
                   $res=OrderLeaseAudit::where('lease_id',$request['leaseId'])->where('id',$audit_id)->update(['check_status'=>1,'update_time'=>time()]);
                   if($res){
                       if($order['sign_no']){
                           $res =  AntchainAtoService::repayWithholdPlan($order['trade_no'],$OrderLease['which_period'],$OrderLease['rent']);
                       }else{
                           $resRule = AntchainService::payRule($order['flow_id']);
                           $resRule=json_decode($resRule['data'],true);
                           $key=$OrderLease['which_period']-1;
                           $res = AntchainService::paysingletradeCancel($order['flow_id'],$resRule['payRules'][$key]['outTradeNo']); //取消智能合同某一期代扣条目
                       }
                       if($res) {
                           //检测逾期订单状态
                           $status = Order::checkOrderOverdueStatus($order['id']);
                           if ($status) {
                               Order::where(['id' => $order['id']])->update(['status' => $status]);
                               CreditCallService::repayInvestData($order['id'], $OrderLease['id']);//上报征信-还款
                           }
                       }

                       return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'提交申请成功');
                   }else{
                       return ReturnMsg(CommonService::HTTP_CODE_FAIL,'更改失败');
                   }
               }
           }
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'提交申请成功');
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'更改失败');
        }
    }





    /**
     * 易付宝扣款
     */
    public function yifubaoPayLease(Request $request){
        if(empty($request['orderId'])||empty($request['leaseId'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
        }

        $userToken = $request->header("SupplierAuth");
        $user = NewAdmin::where(['token'=>$userToken,'type'=>AuthService::MODEL_MERCHANT])->first();
        $user = obToArray($user);

        if(md5($user['mobile'].$request['password']) != $user['password']){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'密码输入错误错误');
        }

        $result = SmsService::checkCode('19357616167', $request['code']);
        if (!$result) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '验证码输入有误');
        }

        $order = Order::from('sp_order_2 as o')
            ->where('o.id',$request['orderId'])
            ->leftjoin('sp_bank_card as b', 'b.uid','o.uid')
            ->leftjoin('sp_order_goods_2 as og','og.order_id','o.id')
            ->select(
                'o.id','o.flow_id','og.pact_type','o.is_skip','o.is_renewal','o.uid','o.trade_no','b.contract_no','b.cert_no','b.bank_name','b.bank_code','b.card_holder_name',
            )
            ->get();

        $order = $order ? $order->toArray() : [];
        if(empty($order)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单不存在');
        }
        if(empty($order[0]['contract_no'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'未签订易付宝协议');
        }
        $OrderLease= OrderLease::where('id',$request['leaseId'])->where('order_id',$request['orderId'])
            ->select(
                'id','which_period','rent','status','paid_rent'
            )
            ->first();
        $OrderLease = $OrderLease ? $OrderLease->toArray() : [];
        if(empty($OrderLease)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单不存在');
        }
        if($OrderLease['status']==1&&!empty($OrderLease['pay_time'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'该期已支付');
        }
        $ispay='';
            foreach ($order as $order){
                $leaseId=$OrderLease['id'];
                $data['notifyUrl'] = config('alipay.callbackDomain').CommonService::NOTICE_XXZ_URL_PAY;
                $data['contractNo']=$order['contract_no'];//'202307267881357'
                $data['goodsName']='主动支付'.$order['trade_no'];
                $data['orderAmount']=sprintf('%.2f',bcsub($OrderLease['rent'],$OrderLease['paid_rent'],2));
                $data['orderName']=base64_encode('主动支付第'.$OrderLease['which_period'].'期');
                $data['outOrderNo']=$order['id'].rand(1000,9999).time();
                $result=SuningPayService::agreementPaymentPay($data);//银行卡协议支付
                if($result['statusCode']=='S'){
                    DB::beginTransaction();
                    //添加记录
                    $insertData = [
                        'trans_id'=>$data['outOrderNo'],
                        'order_id'=>$order['id'],
                        'trade_no'=>$order['trade_no'],
                        'lease_id'=>$OrderLease['id'],
                        'which_period'=>$OrderLease['which_period'],
                        'txn_amt'=>$data['orderAmount'],
                        'create_time'=>date('Y-m-d H:i:s'),
                        'update_time'=>date('Y-m-d H:i:s'),
                        'is_pay'=>YifubaoPay::PAY_YES
                    ];
                    YifubaoPay::insert($insertData);

                    $leaseSave['trade_no']   = $order['trade_no'];
                    $leaseSave['out_order_no'] = $data['outOrderNo'];
                    $leaseSave['pay_time']  = time();
                    $leaseSave['status']    = OrderLease::ORDER_LEASE_STATUS_PAID;
                    $leaseSave['pay_type'] = OrderLease::PAY_TYPE_YIFUBAO;
                    $leaseSave['paid_rent']     = $OrderLease['rent'];

                    if($OrderLease['which_period'] == 1){
                        if($order['is_renewal'] == Order::ORDER_NOT_RENEWAL){
                            if($order['is_skip'] == Order::RISK_SKIP_YES){
                                $arr['status'] = OrderService::ORDER_STATUS_PAY_SUCCESS;
                            }else{
                                $risk_res = ChargeService::RiskCreditUse($order['seller_id'],$order['id'],$order['cert_name'],$order['cert_no'],$order['mobile'],1);
                                $arr['status'] = OrderService::ORDER_STATUS_PAY_SUCCESS;
                            }
                            $user_order_count = Order::where('uid',$order['uid'])->whereIn('status',OrderService::getOrderStatus(OrderService::ORDER_MANUAL_WITHHOLD_OR_PAY))->sum('amount');
                            Order::where('uid',$order['uid'])->whereIn('status',OrderService::getOrderStatus(OrderService::ORDER_MANUAL_WITHHOLD_OR_PAY))->update(['user_order_count'=>$user_order_count]);
                        }else{//续租订单不发货，第一期扣款成功订单状态直接变为租用中
                            if(OrderLease::where([['order_id',$order['id']],['status',OrderLease::ORDER_LEASE_STATUS_PAID]])->count() == $order['month_total']){
                                $arr['status'] = OrderService::ORDER_STATUS_TOBE_RETURNED;
                            }else{
                                $arr['status'] = OrderService::ORDER_STATUS_CONFIRM_GOODS;
                            }
                        }
                        Order::where(['id' => $order['id']])->update($arr);
                        //短信通知
                        ShopSms::orderPlaceSendToShop($order['seller_id'],$order['realname'],$order['trade_no']);
                        ShopSms::orderPaidSendToUser($order['seller_id'],$order['realname'],$order['trade_no'],$OrderLease['rent'],$order['mobile'],$order['id']);
                    }

                    //更改已还租期
                    Order::where(['id' => $order['id']])->increment('month_paid',1);
                    $resulta=OrderLease::where('id',$leaseId)->update($leaseSave);
                    if($resulta){
                        DB::commit();
                    }else{
                        DB::rollBack();
                    }

                    if($order['pact_type'] != GoodsService::GOODS_PACT_TYPE_GIVE){
                        //所有租期已全部支付，状态改为待归还
                        if(OrderLease::where([['order_id',$order['id']],['status',OrderLease::ORDER_LEASE_STATUS_PAID]])->count() == $order['month_total']){
                            Order::where(['id' => $order['id']])->update(['status'=>OrderService::ORDER_STATUS_TOBE_RETURNED]);
                        }
                    }

                    OtherWithholdLog::orderWithholdLog($order['trade_no'],$leaseId,$data['outOrderNo'],$order['trade_no'],$result,OtherWithholdLog::PAY_TYPE_YIFUBAO,true,1);
                    //检测逾期订单状态
                    if($status = Order::checkOrderOverdueStatus($order['id'])){
                        Order::where(['id' => $order['id']])->update(['status'=>$status]);
                    }
                    $ispay=1;
                    break;
                }else{
                    OtherWithholdLog::orderWithholdLog($order['trade_no'],$leaseId,'',$order['trade_no'],$result,OtherWithholdLog::PAY_TYPE_YIFUBAO,false,1);
                }
            }

        if(!empty($ispay)){
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'扣款成功');
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'扣款失败');
        }

    }

    public function getCode(){
        $result=SmsService::sendCode('19357616167');
        if($result){
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '验证码发送成功');
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '验证码发送失败');
        }
    }



    /**
     * 分期部分还款
     */
    public function submitLeasePartial(Request $request)
    {
        if (empty($request['partialAmount']) || empty($request['leaseId']) || empty($request['payType'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '参数错误');
        }

        if (!is_numeric($request['partialAmount'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '金额填写有误');
        }
        $OrderLease = OrderLease::where('id', $request['leaseId'])->where('order_id', $request['orderId'])
            ->select(
                'id', 'which_period', 'status', 'order_id', 'rent', 'overdue_amount'
            )
            ->first();
        $OrderLease = $OrderLease ? $OrderLease->toArray() : [];
        if (empty($OrderLease)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '订单不存在');
        }
        if ($OrderLease['status'] == 1 && !empty($OrderLease['pay_time'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '该期已支付');
        }

        $order = Order::where(['id' => $OrderLease['order_id']])->whereIn('status', OrderService::getOrderStatus(OrderService::ORDER_WITHHOLD_OR_PAY))
            ->select('mini_id', 'trade_no', 'seller_id', 'status', 'pact_url', 'sign_status')->first();
        $order = obToArray($order);
        if (!$order) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '待支付订单不存在');
        }
        if ($order['sign_status'] != 2 || empty($order['pact_url'])) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请签约合同后获取收款码');
        }

        $miniId = $order['mini_id'];
        $order_no = $order['trade_no'];
        $add = [
            'lease_id' => $request['leaseId'],
            'partial_amount' => $request['partialAmount'],
            'pay_type' => $request['payType'],
            'create_time' => time(),
            'reason' => $this->users['username'] . '发起支付',
            'out_trade_no' => $order_no . '|' . time(),
        ];
        $partial_amount = OrderLeasePartial::where('lease_id', $request['leaseId'])->where('status', OrderLeasePartial::STATUS_ISPAY)->sum('partial_amount');
        if (($request['partialAmount'] + $partial_amount) > bcadd($OrderLease['overdue_amount'] + $OrderLease['rent'], 2)) {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '请务大于可还金额');
        }
        $res = OrderLeasePartial::insert($add);

        $options = new QROptions([
            'version' => 4,                             //二维码版本
            'outputType' => QRCode::OUTPUT_IMAGE_JPG,      //生成图片
            'eccLevel' => QRCode::ECC_L,                 //错误级别
            'scale' => 6,                                   //二维码大小
        ]);
        $qrcode = new QRCode($options);


        if ($request['payType'] == OrderLeasePartial::PAY_WXPAY) {
            $res = WechatService::nativeUnifiedorder($OrderLease['id'], $request['partialAmount'], $OrderLease['which_period'], $add['out_trade_no']);
            if ($res['result_code'] == 'SUCCESS') {
                $paycode = $qrcode->render($res['code_url']);
            }
            $img = 'img/wxpay.png';
        }

        if ($request['payType'] == OrderLeasePartial::PAY_ALIPAY) {
            $params = [
                'order_no' => $add['out_trade_no'],
                'order_id' => $OrderLease['order_id'],
                'lease_id' => $OrderLease['id'],
                'which_period' => $OrderLease['which_period'],
                'totalAmount' => $request['partialAmount'],
            ];
            $res = AlipayService::alipayOrderLeasePay($miniId, $params);

            if ($res['status']) {
                $paycode = $qrcode->render($res['data']['qr_code']);
            }
            $img = 'img/alipay.png';
        }

        $canvas = Image::canvas(450, 550);
        $head = Image::make(public_path($img))
            ->resize(450, 550);

        $canvas->insert($head, 'top-left', 0, 0)
            ->insert($paycode, 'top-left', 98, 238);
//        $canvas->response('data-url', 90);
//        //var_dump($canvas->encode()->getEncoded());
//
//        $paycode=$canvas->encode();
        $paycode = $canvas->response('data-url', 90);
        $paycode = json_encode($paycode);
        $paycode = json_decode($paycode, true);
        if ($res) {
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS, '提交申请成功', $paycode['original']);
        } else {
            return ReturnMsg(CommonService::HTTP_CODE_FAIL, '更改失败');
        }
    }



    /**
     * 结算价买断
     */
    public function submitOrderBuyOut(Request $request){
//        dd($request);
        if((empty($request['amount'])&&empty($request['reduced_amount']))||empty($request['orderId'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'参数错误');
        }
        $userToken = $request->header("SupplierAuth");
        $user = NewAdmin::where(['token'=>$userToken,'type'=>AuthService::MODEL_MERCHANT])->first();
        $user = obToArray($user);

        if(md5($user['mobile'].$request['password']) != $user['password']){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'密码输入错误错误');
        }

        if(!empty($request['reduced_amount'])&&!empty($request['amount'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'优惠金额或买断金额填其一');
        }
        if(empty($request['reduced_amount'])&&empty($request['amount'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'优惠金额或买断金额填其一');
        }

        if(!empty($request['reduced_amount'])&&!is_numeric($request['reduced_amount'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'金额填写有误');
        }
        if(!empty($request['amount'])&&!is_numeric($request['amount'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'金额填写有误');
        }

        if(!empty($request['reduced_amount'])){
            $one=OrderLease::where('order_id',$request['orderId'])->where('status','<>',OrderLease::ORDER_LEASE_STATUS_PAID)->first();
            if($one){
                return ReturnMsg(CommonService::HTTP_CODE_FAIL,'账单用户未支付完成');
            }
        }


        $order= Order::from('sp_order_2 as o')
            ->where('o.id',$request['orderId'])
            ->leftJoin('sp_order_goods_2 as og','og.order_id','=','o.id')
            ->whereIn('o.status',array_merge(OrderService::getOrderStatus(OrderService::ORDER_WITHHOLD_OR_PAY),['60']))
            ->select('o.id','o.status','o.sign_status','o.pact_url','og.pact_type')
            ->first();
        $order = $order ? $order->toArray() : [];
        if(empty($order)){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'订单不存在');
        }
        if(!in_array($order['status'],['30','38','39','42','60'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'该状态不支持买断结算');
        }
        if ($order['sign_status']!=2||empty($order['pact_url'])){
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请签约合同后提交');
        }
        $add = [
            'order_id'=>$request['orderId'],
            'amount'=>$request['amount'],
            'reduced_amount'=>$request['reduced_amount'],
            'sub_remark'=>$request['remark'],
            'image_path'=>$request['image_path'],
            'create_time'=>time(),
            'admin_id'=>$user['id']
        ];
        $rent= OrderLease::where('order_id',$request['orderId'])->where('status','<>',1)->sum('rent');
        $overdue_amount= OrderLease::where('order_id',$request['orderId'])->where('status','<>',1)->sum('overdue_amount');

        $orderGood=OrderGoods::where('order_id',$order['id'])->select('id','setmeal_price','pact_type')
            ->first();

        if($orderGood['pact_type']!='2'){
            $total=bcadd($rent+$overdue_amount,$orderGood['setmeal_price'],2);
        }else{
            $total=bcadd($rent,$overdue_amount,2);
        }

//        if($total<$request['amount']&&$order['pact_type']==2){
//            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'请务大于剩余租金总额');
//        }
        $res=OrderBuyoutAudit::insert($add);

        if($res){
            return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'提交申请成功');
        }else{
            return ReturnMsg(CommonService::HTTP_CODE_FAIL,'更改失败');
        }
    }



}
